import { getSetting,chooseAddress,openSetting,showModal,showToast,requestPayment} from '../../utils/asyncWx.js'
import {request} from '../../request/index.js'
Page({
    data:{
        address:{},
        cart:[],
        totalPrice:0,
        totalNum:0
    },
    onShow(){
        const address=wx.getStorageSync("address")
        // 获取缓存中的购物车数据
        let cart=wx.getStorageSync('cart')||[]
        // 过滤过得购物车数组
        cart=cart.filter(v=>v.checked)
        this.setData({address})
        // 总价格 总数量
        let totalPrice=0
        let totalNum=0
        cart.forEach(v => {
            totalPrice+=v.num*v.goods_price
            totalNum+=v.num
        });
        this.setData({
            cart,
            totalPrice,
            totalNum,
            address
        }) 
    },

    // 点击支付
    async handleOrderPay(){
        try {
            // 判断缓存中有没有token
            const token=wx.getStorageSync("token")
            if(!token){
                wx.navigateTo({
                    url: '/pages/auth/index',
                });
                return
            }
            // 创建订单
            // 准备请求头参数
            const header={Authorization:token}
            const order_price=this.data.totalPrice
            const consignee_addr=this.data.address.all
            const cart=this.data.cart
            let goods=[]
            cart.forEach(v=>goods.push({
                goods_id:v.goods_id,
                goods_number:v.num,
                goods_price:v.goods_price
            }))
            const orderParams={order_price,consignee_addr,goods}
            // 准备发送请求 创建订单
            let {order_number}=await request({url:'/my/orders/create',method:'post',data:orderParams,header:header})
            // 发起预支付接口
            const {pay} =await request({url:'/my/orders/req_unifiedorder',method:'POST',header,data:{order_number}})
            // 发起微信支付
            // (因为这个token要用企业微信，视频中的黑马老师的appid才可以，从评论区拿到的token用这个接口去发送请求会显示没有权限)
            // 先用其他代替
            wx.showToast({title:'支付成功！'});
            // 手动删除缓存中已经支付了的商品
            let newCart=wx.getStorageSync('cart')
            console.log('原始:',newCart);
            newCart=newCart.filter(v=>!v.checked)
            console.log('之后:',newCart);
            wx.setStorageSync('cart',newCart)
            // 支付成功跳转到订单页面
            wx.navigateTo({
                url:'/pages/order/index'
            })
            // const res=await requestPayment(pay)
            // console.log(res);
        } catch (error) {
            console.log(error)
        } 
    }
})